//
//  HWpingjiajiemianViewController.m
//  HWanGame
//
//  Created by 陈道斌 on 2021/8/19.
//  Copyright © 2021 Chendaobin. All rights reserved.
//

#import "HWpingjiajiemianViewController.h"
#import "LFOpinionView.h"
#import <CTAssetsPickerController.h>
#import "ChooseCollectionViewCell.h"
#import "HWLoginController.h"
// 项目中黑色字体的颜色
#define    wholeProjectBlackFontColor  RGB(51,51,51)
#define MAX_LIMIT_NUMS 300
@interface HWpingjiajiemianViewController ()<UITextViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,CTAssetsPickerControllerDelegate,ChooseCollectionViewCellDelegate,UITextFieldDelegate,UINavigationControllerDelegate>{
    
    NSInteger  max;
    
}

@property(strong,nonatomic) UIView *baiseView;
@property(strong,nonatomic) UIView *pingfenView;
@property(assign,nonatomic) int xuanzhong;
@property(strong,nonatomic) UIView *huisegrayView;
@property (nonatomic, strong) LFOpinionView *textView;

@property(strong,nonatomic) UICollectionView *collectionView;
@property(strong,nonatomic) NSMutableArray *dataMuArry;
@property(strong,nonatomic) NSMutableArray *cunchuUrlStrMutabelArr;


@end

@implementation HWpingjiajiemianViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setupTheData];
    [self setupNavigionview];
    [self initView];
    
    // 全部评论
    
    
    
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}
#pragma  mark  --------- 设置数据
- (void)setupTheData {
    max = 9;
    self.dataMuArry =  [[NSMutableArray alloc]init];
   // NSDictionary *dic = @{@"iconImage":@"", @"isdelete":@"0"};
 //   CasesIconItem  *p1 = [CasesIconItem mj_objectWithKeyValues:dic];
    CasesIconItem  *p1 = [[CasesIconItem alloc]init];
    p1.iconImage = [UIImage imageNamed:@""];
    [self.dataMuArry addObject:p1];
    
    

}


// 评价界面
- (void)setupNavigionview {

    self.navigationItem.title = @"评价";
    self.view.backgroundColor = RGB(245, 245, 245);
    UIButton *fabuBut = [UIButton buttonWithType:UIButtonTypeCustom];
    fabuBut.frame = CGRectMake(0, 0, 50, 26);
    fabuBut.backgroundColor = RGB(247, 124, 47);
    [fabuBut setTitle:@"发表" forState:UIControlStateNormal];
    [fabuBut setTitleColor:RGB(255, 255, 255) forState:UIControlStateNormal];
    fabuBut.layer.cornerRadius = 2;
    fabuBut.layer.masksToBounds = YES;
    [fabuBut  addTarget:self action:@selector(fabuButTap) forControlEvents:UIControlEventTouchUpInside];
     self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:fabuBut];
    
    
    
    
    
    
    
    
    
}

// 发布按钮
- (void)fabuButTap {
    
    [self shujushanchuantupian];
    
    
    
}









-(void)initView  {
    
    self.baiseView = [[UIView alloc]initWithFrame:CGRectMake(0, CF_NavHeight+10, kScreenW, kScreenH-CF_NavHeight-10)];
    self.baiseView.backgroundColor = RGB(255, 255, 255);
    [self.view addSubview:self.baiseView];
    
    // 全部评论
    
    
//    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(15,17, 60, 25)];
//
//        //   label.autoresizingMask = UIViewAutoresizingFlexibleWidth;
//
//    label.textColor = RGB(51, 51, 51);
//          // label.shadowColor = [UIColor colorWithWhite:.9f alpha:1.0f];
//          //label.shadowOffset = CGSizeMake(0.0f, 1.0f);
//     label.backgroundColor = [UIColor clearColor];
//          //        label.textAlignment = UITextAlignmentLeft;
//     label.text = @"请打分";
//    [self.baiseView addSubview:label];
    
    
    UIView  *pingfenView = [[UIView alloc]initWithFrame:CGRectMake(0, 17, kScreenW, 25)];
    pingfenView.backgroundColor = [UIColor whiteColor];
    self.pingfenView  = pingfenView;
    [self.baiseView addSubview:pingfenView];



         UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(15,0, 55, 25)];
        label1.font = [UIFont systemFontOfSize:16];

       //   label.autoresizingMask = UIViewAutoresizingFlexibleWidth;

         label1.textColor = RGB(51, 51, 51);
         // label.shadowColor = [UIColor colorWithWhite:.9f alpha:1.0f];
         //label.shadowOffset = CGSizeMake(0.0f, 1.0f);
         label1.backgroundColor = [UIColor whiteColor];
         //        label.textAlignment = UITextAlignmentLeft;
         label1.text = @"请评分";
         [pingfenView  addSubview:label1];


      for (int i =0; i < 5 ; i++) {
  
         UIButton   *buton = [UIButton buttonWithType:UIButtonTypeCustom];
         buton.frame = CGRectMake(15+55+5+i*26+i*10, 0, 26, 24);
         [buton setTitleColor:RGB(255, 255, 255) forState:UIControlStateNormal];
       //  self.recommendedBut.backgroundColor = [UIColor redColor];
         [buton setBackgroundImage:[UIImage imageNamed:@"zuixingweibenxuanzhong"] forState:UIControlStateNormal];
         [buton setBackgroundImage:[UIImage imageNamed:@"xingxingico"] forState:UIControlStateSelected];
          [buton setBackgroundImage:[UIImage imageNamed:@"xingxingico"] forState:UIControlStateHighlighted];
         [buton addTarget:self action:@selector(tuijianTap:) forControlEvents:UIControlEventTouchUpInside];
         buton.tag = i+100;
         [pingfenView addSubview:buton];
      
          
      
    }


    self.xuanzhong = 0;
    self.huisegrayView = [[UIView alloc] initWithFrame:CGRectMake(15, 70, kScreenW-30, 150+80*1+10)];
    self.huisegrayView.backgroundColor = RGB(245, 245, 245);
    self.huisegrayView.layer.cornerRadius = 5;
    self.huisegrayView.layer.masksToBounds= YES;
    [self.baiseView addSubview:self.huisegrayView];
    
    _textView = [[LFOpinionView alloc] init];
    _textView.alwaysBounceVertical = YES;
    _textView.delegate = self;
    //     _textView.x = 10;
    //     _textView.y = 0;
    _textView.frame = CGRectMake(10, 0, kScreenW- 50, 150);
    _textView.backgroundColor = [UIColor whiteColor];
    _textView.backgroundColor = RGB(245, 245, 245);
    _textView.textColor = RGB(51, 51, 51);
    _textView.placeholder = @"你可以从玩法、画质、福利、氪金性价比等方面分享～";
    _textView.font = [UIFont systemFontOfSize:12];
    _textView.layer.cornerRadius =10 ;
    _textView.layer.masksToBounds = YES;
    [self.huisegrayView addSubview:_textView];
    
    [self createCollectionView];
    

    
    
}


- (void)tuijianTap:(UIButton *)sender {
    
  
    if (sender.tag == 100) {
        
        
        UIButton     *button =   [self.pingfenView viewWithTag:100];
        UIButton     *button1 =   [self.pingfenView viewWithTag:101];
        UIButton     *button2 =   [self.pingfenView viewWithTag:102];
        UIButton     *button3 =   [self.pingfenView viewWithTag:103];
        UIButton     *button4 =   [self.pingfenView viewWithTag:104];
        
        button.selected = YES;
        button1.selected = NO;
        button2.selected = NO;
        button3.selected = NO;
        button4.selected = NO;
        self.xuanzhong = 1;
        
  
     
        
    } else if (sender.tag == (1+100)) {
        
           
       
        UIButton     *button =   [self.pingfenView viewWithTag:100];
        UIButton     *button1 =   [self.pingfenView viewWithTag:101];
        UIButton     *button2 =   [self.pingfenView viewWithTag:102];
        UIButton     *button3 =   [self.pingfenView viewWithTag:103];
        UIButton     *button4 =   [self.pingfenView viewWithTag:104];
        
        button.selected = YES;
        button1.selected = YES;
        button2.selected = NO;
        button3.selected = NO;
        button4.selected = NO;
        self.xuanzhong = 2;

         
         

        
        
    } else if (sender.tag == (2+100)) {
        
        
        UIButton     *button =   [self.pingfenView viewWithTag:100];
        UIButton     *button1 =   [self.pingfenView viewWithTag:101];
        UIButton     *button2 =   [self.pingfenView viewWithTag:102];
        UIButton     *button3 =   [self.pingfenView viewWithTag:103];
        UIButton     *button4 =   [self.pingfenView viewWithTag:104];
        
        button.selected = YES;
        button1.selected = YES;
        button2.selected = YES;
        button3.selected = NO;
        button4.selected = NO;
        
        self.xuanzhong = 3;
        
        
        
           
        
        
    } else if (sender.tag == (3+100)) {
        
        
        UIButton     *button =   [self.pingfenView viewWithTag:100];
        UIButton     *button1 =   [self.pingfenView viewWithTag:101];
        UIButton     *button2 =   [self.pingfenView viewWithTag:102];
        UIButton     *button3 =   [self.pingfenView viewWithTag:103];
        UIButton     *button4 =   [self.pingfenView viewWithTag:104];
        
        button.selected = YES;
        button1.selected = YES;
        button2.selected = YES;
        button3.selected = YES;
        button4.selected = NO;
        
        self.xuanzhong = 4;
        
        
        
       
        
        
        
        
        
        
        
    } else if (sender.tag == (4+100)) {
        
        
        UIButton     *button =   [self.pingfenView viewWithTag:100];
        UIButton     *button1 =   [self.pingfenView viewWithTag:101];
        UIButton     *button2 =   [self.pingfenView viewWithTag:102];
        UIButton     *button3 =   [self.pingfenView viewWithTag:103];
        UIButton     *button4 =   [self.pingfenView viewWithTag:104];
        
        button.selected = YES;
        button1.selected = YES;
        button2.selected = YES;
        button3.selected = YES;
        button4.selected = YES;
        
        self.xuanzhong = 5;
        
        
        
        
        
        
    }
    
    
    
    
    
    
}



- (void)createCollectionView {
    UICollectionViewFlowLayout *fl = [[UICollectionViewFlowLayout alloc]init];
    self.collectionView =  [[UICollectionView alloc]initWithFrame:CGRectMake(10, 150, kScreenW -50, 80*3+30+10) collectionViewLayout:fl];
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    [self.huisegrayView addSubview:self.collectionView];
   // CGFloat spe =  (QCScreenW-62*4 - 30)/3;
    fl.minimumInteritemSpacing = 10;
    fl.minimumLineSpacing = 15;
    _collectionView.backgroundColor = RGB(245, 245, 245);
    
   // [_collectionView registerClass:[PositioningCollectionView class] forCellWithReuseIdentifier:@"JXCell"];
    
    [_collectionView registerNib:[UINib nibWithNibName:@"ChooseCollectionViewCell" bundle:nil] forCellWithReuseIdentifier: @"JXCell"];
   // PositioningCollectionView
}


- (void)ChooseCollectionViewDelegate:(ChooseCollectionViewCell *)cell {
    NSIndexPath *inde = [self.collectionView indexPathForCell:cell];
    [self.dataMuArry removeObjectAtIndex:inde.row];
    max = max + 1;
    [self.collectionView reloadData];
    
    NSUInteger lieshu = self.dataMuArry.count -1;
    
    if (lieshu/4 == 0  ) {
        
        self.huisegrayView.frame = CGRectMake(15, 70, kScreenW-30, 150+80*1+10);
        
        
    } else if (lieshu/4 == 1) {
        
        self.huisegrayView.frame = CGRectMake(15, 70, kScreenW-30, 150+80*2+30);
        
    } else {
        
        self.huisegrayView.frame = CGRectMake(15, 70, kScreenW-30, 150+80*3+40);
        
    }
    
    
    
    
    
    
    
    
}


//定义展示的UICollectionViewCell的个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataMuArry.count;
}
//定义展示的Section的个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

//每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * CellIdentifier =@"JXCell";
 //   ChooseCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    ChooseCollectionViewCell *cell =  [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
    
    cell.choosedelegate = self;
    cell.model = self.dataMuArry[indexPath.row];
    return cell;
    
    
    
    
}

//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(80, 80);
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    //  UIEdgeInsetsMake(<#CGFloat top#>, <#CGFloat left#>, <#CGFloat bottom#>, <#CGFloat right#>)
    return UIEdgeInsetsMake(0, 0, 0, 0);
}





- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
     CasesIconItem  *model  = self.dataMuArry[indexPath.row];
    if (model.isdelete == NO) {
        [self setUPUserImage];
    } else {
        
    }
    
    
}




#pragma  mark  ------------  点击更换头像
- (void)setUPUserImage {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *videoAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        //
        if (max < 1) {
            [MBProgressHUD showError:@"图片上床只能大于九张"];
            return;
        }
        [self picturesImage];
    }];
    [videoAction setValue:wholeProjectBlackFontColor forKey:@"_titleTextColor"];
    UIAlertAction *gifAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
       // [self photoAlbumImage];
        if (max < 1) {
            [MBProgressHUD showError:@"图片上床只能小于九张"];
            return;
        }
        [self selectPhoto];
    }];
    
    // KVC 改变颜色
    [gifAction setValue:wholeProjectBlackFontColor forKey:@"_titleTextColor"];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        
    }];
    // KVC 改变颜色
    [cancelAction setValue:wholeProjectBlackFontColor forKey:@"_titleTextColor"];
    
    [alert addAction:videoAction];
    [alert addAction:gifAction];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:nil];
    
    
}






//点击拍照
- (void)picturesImage {
    
    
    
    
    BOOL result = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
    
    if (result) {
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate = self;
        imagePicker.allowsEditing = YES;
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:imagePicker animated:YES completion:nil];
        
        
    }else{
        //        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请在设置-->隐私-->相机，中开启本应用的相机访问权限！！" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"我知道了", nil];
        //        [alert show];
        
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请在设置-->隐私-->相机，中开启本应用的相机访问权限！！" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *videoAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            
        }];
        [videoAction setValue:wholeProjectBlackFontColor forKey:@"_titleTextColor"];
        UIAlertAction *gifAction = [UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            
        }];
        // KVC 改变颜色
        [gifAction setValue:wholeProjectBlackFontColor forKey:@"_titleTextColor"];
        [alert addAction:videoAction];
        [alert addAction:gifAction];
        [self presentViewController:alert animated:YES completion:nil];
        //
        
        
    }
    
    
}


////点击相册
//- (void)photoAlbumImage {
//
//    BOOL result = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary];
//    if (result) {
//        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
//        imagePicker.delegate = self;
//        imagePicker.allowsEditing = YES;
//        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//        //                        [self presentModalViewController:imagePicker animated:YES];
//        [self presentViewController:imagePicker animated:YES completion:nil];
//    }else{
//        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请在设置-->隐私-->相机，中开启本应用的相机访问权限！！" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"我知道了", nil];
//        [alert show];
//    }
//
//
//}


#pragma  mark ---------  UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey, id> *)info {
    UIImage *userImage = [self fixOrientation:(UIImage *)info[UIImagePickerControllerEditedImage]];
    // UIImagePickerControllerOriginalImage

    
    // 图片缩放
    userImage = [self scaleImage:userImage toScale:0.3];
    
    max = max - 1;
   
    CasesIconItem  *p1 = [[CasesIconItem alloc]init];
    p1.iconImage = userImage;
    p1.isdelete = YES;
    //self.dataMuArry.count - 1
    [self.dataMuArry insertObject:p1 atIndex:self.dataMuArry.count - 1];
    [self.collectionView reloadData];
    
    
    NSUInteger lieshu = self.dataMuArry.count -1;
    if (lieshu/4 == 0  ) {
        
        self.huisegrayView.frame = CGRectMake(15, 70, kScreenW-30, 150+80*1+10);
        
        
    } else if (lieshu/4 == 1) {
        
        self.huisegrayView.frame = CGRectMake(15, 70, kScreenW-30, 150+80*2+30);
        
    } else {
        
        self.huisegrayView.frame = CGRectMake(15, 70, kScreenW-30, 150+80*3+40);
        
    }
    

    //    照片上传
    // [self upDateHeadIcon:userImage];
    //保存图片 保存到沙河
    //   [self saveImage:userImage name:@"touxiang"];
    
    // QrCodeableViewCell *qrCodCell = [tableView dequeueReusableCellWithIdentifier:qrCodID];

    //往配图相册view里面添加图片
    [picker dismissViewControllerAnimated:YES completion:nil];
}

//- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo{
//    //    修正照片方向(手机转90度方向拍照)
//    UIImage *userImage = [self fixOrientation:[editingInfo objectForKey:@"UIImagePickerControllerOriginalImage"]];
//
//    // 图片缩放
//    userImage = [self scaleImage:userImage toScale:0.3];
//
//    //    照片上传
//   // [self upDateHeadIcon:userImage];
//    //保存图片 保存到沙河
//  //   [self saveImage:userImage name:@"touxiang"];
//
//    //往配图相册view里面添加图片
//    [picker dismissViewControllerAnimated:YES completion:nil];
//}


//修正照片方向(手机转90度方向拍照)
- (UIImage *)fixOrientation:(UIImage *)aImage {
    
    // No-op if the orientation is already correct
    if (aImage.imageOrientation == UIImageOrientationUp)
        return aImage;
    
    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                             CGImageGetBitsPerComponent(aImage.CGImage), 0,
                                             CGImageGetColorSpace(aImage.CGImage),
                                             CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;
    }
    
    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}

//缩放图片
- (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize
{
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width*scaleSize,image.size.height*scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height *scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSLog(@"%@",NSStringFromCGSize(scaledImage.size));
    return scaledImage;
}

//保存照片到沙盒路径(保存)
- (void)saveImage:(UIImage *)image name:(NSString *)iconName
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    //写入文件
    NSString *icomImage = iconName;
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png", icomImage]];
    // 保存文件的名称
    //    [[self getDataByImage:image] writeToFile:filePath atomically:YES];
    [UIImagePNGRepresentation(image) writeToFile: filePath  atomically:YES];
}

//上传图片
- (void)upDateHeadIcon:(UIImage *)photo
{
    if (photo == nil) {
        return;
    }
    
    
}




- (void )selectPhoto {
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status){
        if (status != PHAuthorizationStatusAuthorized) return;
        
        dispatch_async(dispatch_get_main_queue(), ^{
            // 弹出图片选择界面
            CTAssetsPickerController *picker = [[CTAssetsPickerController alloc] init];
            // 隐藏空相册
            picker.showsEmptyAlbums = NO;
            // 显示图片索引
            picker.showsSelectionIndex = YES;
            
            picker.assetCollectionSubtypes = @[
                                               @(PHAssetCollectionSubtypeSmartAlbumUserLibrary),
                                               @(PHAssetCollectionSubtypeAlbumRegular),

                                               ];
            
            
//            picker.assetCollectionSubtypes = @[
//                                               @(PHAssetCollectionSubtypeSmartAlbumVideos),
//
//
//                                               ];
//
            picker.delegate = self;
            
            if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { // 如果当前运行的设备是平板电脑
                picker.modalPresentationStyle = UIModalPresentationFormSheet;
            }
            
            [self presentViewController:picker animated:YES completion:nil];
        });
    }];
}

#pragma mark - <CTAssetsPickerControllerDelegate>
- (BOOL)assetsPickerController:(CTAssetsPickerController *)picker shouldSelectAsset:(PHAsset *)asset
{
   // NSInteger max = 9;
    
    if (picker.selectedAssets.count < max) return YES;
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"注意"
                                                                   message:[NSString stringWithFormat:@"最多选择%zd张图片", max]
                                                            preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:nil]];
    // 这里一定要用picker，不能使用self（因为当前显示在上面的控制器是picker，不是self）
    [picker presentViewController:alert animated:YES completion:nil];
    
    return NO;
}

/**
 *  选择完毕的时候调用
 */
- (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSArray *)assets
{
    // 关闭图片选择界面
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    // 选择图片时的配置项
    PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
    options.resizeMode   = PHImageRequestOptionsResizeModeExact;
    options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
    
    // 显示图片
    for (NSInteger i = 0; i < assets.count; i++) {
        PHAsset *asset = assets[i];
        CGSize size = CGSizeMake(asset.pixelWidth / [UIScreen mainScreen].scale, asset.pixelHeight / [UIScreen mainScreen].scale);
        
        // 请求图片
        [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:size contentMode:PHImageContentModeDefault options:options resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
            // 添加图片控件
//            UIImageView *imageView = [[UIImageView alloc] init];
//            imageView.image = result;
//            [self.view addSubview:imageView];
//
//            imageView.frame = CGRectMake((i % 3) * (100 + 10), (i / 3) * (100 + 10), 100, 100);
            CasesIconItem  *p1 = [[CasesIconItem alloc]init];
            
            
            
            p1.iconImage = result;
            p1.isdelete = YES;
            //self.dataMuArry.count - 1
            max = max - 1;
            [self.dataMuArry insertObject:p1 atIndex:self.dataMuArry.count - 1];
            [self.collectionView reloadData];
            NSUInteger lieshu = self.dataMuArry.count -1;
            
            if (lieshu/4 == 0  ) {
                
                self.huisegrayView.frame = CGRectMake(15, 70, kScreenW-30, 150+80*1+10);
                
                
            } else if ( lieshu/4 == 1) {
                
                self.huisegrayView.frame = CGRectMake(15, 70, kScreenW-30, 150+80*2+30);
                
            } else {
                
                self.huisegrayView.frame = CGRectMake(15, 70, kScreenW-30, 150+80*3+40);
                
            }
           
            
            
            
            
        }];
    }
}



- (NSString*)encodeToBase64String:(UIImage*)image {

    return [UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    
    

}


// 数据上传图片

- (void)shujushanchuantupian {
    
   
    if (!(_textView.text.length > 0)) {
      
        [MBProgressHUD showError:@"请输入内容"];
        return;
        
    }
    
    if(self.xuanzhong == 0 ) {
        
        [MBProgressHUD showError:@"请选择评分"];
        
        return;
        
    }
    
    if ([[HWLocallyStoredData getLoginUserID] isEqualToString:@""]) {
        
          HWLoginController  *login = [[HWLoginController alloc]init];
            [self.navigationController pushViewController:login animated:YES];
           return;
    
    }
    
    
    

 
    
    self.cunchuUrlStrMutabelArr = [[NSMutableArray alloc]init];
    
    
    
    if (self.dataMuArry.count == 0) {
        [MBProgressHUD  hideHUD];
        
        return;
    }
    
    if (self.dataMuArry.count == 1 ) {
        
        [self wutupianshanch];
        
        return;
    }
    
    
     [MBProgressHUD showMessage:@"正在提交...."];
    
    for (int i = 0; i < (self.dataMuArry.count-1); i++) {
           
           CasesIconItem *ite = self.dataMuArry[i];
        
           AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
                   //接收类型不一致请替换一致text/html或别的
                   manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                                        @"text/html",
                                                                        @"image/jpeg",
                                                                        @"image/png",
                                                                        @"application/octet-stream",
                                                                        @"text/json",
                                                                        nil];

                  NSString *userID = [HWLocallyStoredData getLoginUserID];
        
                  int t =   [WMUtil  getRandomNumber:101 to:998];
              NSString *tStr = [NSString stringWithFormat:@"%ld%d",[WMUtil getTimeSp],t];
              NSString *sign = [NSString stringWithFormat:@"%@%@%@",userID,tStr,@"fsd213ewdsadqwe2121213edsad"];


              NSString *signMD5 = [WMUtil md5HexDigest:sign];




              NSDictionary *dic = @{@"uid":[HWLocallyStoredData getLoginUserID],@"t":tStr,@"sign":signMD5,@"image":@"image"};


                   //AppDelegate *myDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
                  // NSDictionary *dic = @{@"id":myDelegate.userId};
                  manager.responseSerializer = [AFHTTPResponseSerializer serializer];

                  NSString *url = [NSString stringWithFormat:@"%@?ct=app&ac=upload",[HWOCGlobalConst baseUrl]];
                  
       
           NSURLSessionDataTask *task =   [manager POST:url parameters:dic headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
               
               NSData *imageDatas = UIImageJPEGRepresentation(ite.iconImage,1.0f);;
               NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
               formatter.dateFormat = @"yyyyMMddHHmmss";
               NSString *str = [formatter stringFromDate:[NSDate date]];
               NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
               //上传的参数(上传图片，以文件流的格式)
               [formData appendPartWithFileData:imageDatas
                                           name:@"image"
                                       fileName:fileName
                                       mimeType:@"image/jpeg"];
            
           } progress:^(NSProgress * _Nonnull uploadProgress) {
               NSLog(@"上传进度");
               NSLog(@"%@",uploadProgress);
           } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
               
               //上传成功
               NSLog(@"上传成功");
               NSLog(@"%@",responseObject);
              NSString * str  =[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];

               [self.cunchuUrlStrMutabelArr addObject:str];

               if (self.cunchuUrlStrMutabelArr.count == (self.dataMuArry.count-1) ) {
                   NSLog(@"vfijvijf");
                   [MBProgressHUD  hideHUD];
                 [self zuizhongshanchunchenggonghou];

                 //   [MBProgressHUD  hideHUD];

               } else {

                    [MBProgressHUD  hideHUD];

               }

               NSLog(@"上传成功");
               NSLog(@"上传成功");
              //  [self chuanURldaohoutai:str];
          } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
              //上传失败
              NSLog(@"上传失败");

              [MBProgressHUD  hideHUD];
         }];
        
        
        

//                   NSURLSessionDataTask *task = [manager POST:url parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
//
//                       NSData *imageDatas = UIImageJPEGRepresentation(ite.iconImage,1.0f);;
//                       NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//                       formatter.dateFormat = @"yyyyMMddHHmmss";
//                       NSString *str = [formatter stringFromDate:[NSDate date]];
//                       NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
//                       //上传的参数(上传图片，以文件流的格式)
//                       [formData appendPartWithFileData:imageDatas
//                                                   name:@"image"
//                                               fileName:fileName
//                                               mimeType:@"image/jpeg"];
//                   } progress:^(NSProgress * _Nonnull uploadProgress) {
//                       //打印下上传进度
//                       NSLog(@"上传进度");
//                       NSLog(@"%@",uploadProgress);
//                   } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//                       //上传成功
//                       NSLog(@"上传成功");
//                       NSLog(@"%@",responseObject);
//                      NSString * str  =[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
//
//                       [self.cunchuUrlStrMutabelArr addObject:str];
//
//                       if (self.cunchuUrlStrMutabelArr.count == (self.dataMuArry.count-1) ) {
//                           NSLog(@"vfijvijf");
//                           [MBProgressHUD  hideHUD];
//                         [self zuizhongshanchunchenggonghou];
//
//                         //   [MBProgressHUD  hideHUD];
//
//                       } else {
//
//                            [MBProgressHUD  hideHUD];
//
//                       }
//
//                       NSLog(@"上传成功");
//                       NSLog(@"上传成功");
//                      //  [self chuanURldaohoutai:str];
//
//
//                   } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//                       //上传失败
//                       NSLog(@"上传失败");
//
//                       [MBProgressHUD  hideHUD];
//                   }];
//        
          
        
        
           
    }
 
      
    
    
    
    
   

    
    
    
    
}


//最终请求数据
- (void)zuizhongshanchunchenggonghou {
    
       
       
   
       
       
       
       NSString *userID = [HWLocallyStoredData getLoginUserID];
       int t = [WMUtil getRandomNumber:101 to:998];
       NSString *tStr = [NSString stringWithFormat:@"%ld%d",[WMUtil getTimeSp],t];
       NSString *sign = [NSString stringWithFormat:@"%@%@%@",userID,tStr,@"fsd213ewdsadqwe2121213edsad"];
       NSString *signMD5 = [WMUtil md5HexDigest:sign];
       

       NSMutableArray * arr = [[NSMutableArray alloc]init];
       
    
     for (int i = 0 ; i < self.cunchuUrlStrMutabelArr.count; i++) {
         
           [arr addObject:self.cunchuUrlStrMutabelArr[i]];
         
        
      }
       
       
       
       NSString *ico =    [self  gs_jsonStringCompactFormatForNSArray:arr];
      NSString *pointStr  = [NSString stringWithFormat:@"%d",self.xuanzhong*2];
    
       
       NSDictionary *parametes = @{
                                   @"ct" : @"app2021",
                                   @"ac" : @"gameinfo_pinglun",
                                   @"ios" : @"1",
                                   @"id" :self.gameIDStr,
                                   @"uid" :userID,
                                   @"t" :tStr,
                                   @"sign":signMD5,
                                   @"content": _textView.text,
                                   @"images":ico,
                                   @"point": pointStr,
                                   @"pid":@"0",
                                   
                                 
                                   };
        //  @"images" :ico,
       
       [MBProgressHUD showMessage:@"正在提交...."];
       [HWWebUtils doPostWithParameters:parametes progress:nil success:^(id response) {
           
           NSString *codeStr =  [NSString stringWithFormat:@"%@",response[@"code"]];
             //   [MBProgressHUD hideHUD];
                
                
                if ([codeStr intValue] == 1) {
                 
                    [self.navigationController popViewControllerAnimated:YES];
                    [MBProgressHUD  showError:@"提交成功"];
       

                } else {
                    
                     [MBProgressHUD  showError:response[@"message"]];
                    
                }
                NSLog(@"%@",response);
           
       } failure:^(NSString *error) {
            [MBProgressHUD  showError:@"加载失败"];
    
       }];
    
    
    
    
    
    
    
    
    
    
}

// 没有图片上传

- (void)wutupianshanch {
    
    
    
    NSString *userID = [HWLocallyStoredData getLoginUserID];
    

    
    
    int t = [WMUtil getRandomNumber:101 to:998];
    NSString *tStr = [NSString stringWithFormat:@"%ld%d",[WMUtil getTimeSp],t];
    NSString *sign = [NSString stringWithFormat:@"%@%@%@",userID,tStr,@"fsd213ewdsadqwe2121213edsad"];
    NSString *signMD5 = [WMUtil md5HexDigest:sign];
    

//    NSMutableArray * arr = [[NSMutableArray alloc]init];
//
//    for (int i = 0 ; i < self.cunchuUrlStrMutabelArr.count; i++) {
//
//        [arr addObject:self.cunchuUrlStrMutabelArr[i]];
//
//
//     }
//
//    NSString *ico =    [self  gs_jsonStringCompactFormatForNSArray:arr];
//
  NSString *pointStr  = [NSString stringWithFormat:@"%d",self.xuanzhong];
//
    
    NSDictionary *parametes = @{
                                @"ct" : @"app2021",
                                @"ac" : @"gameinfo_pinglun",
                                @"ios" : @"1",
                                @"id" :self.gameIDStr,
                                @"uid" :userID,
                                @"t" :tStr,
                                @"sign":signMD5,
                                @"content": _textView.text,
                                @"point": pointStr,
                                @"pid":@"0",
                                
                
                              
                                };
     //  @"images" :ico,
    
    [MBProgressHUD showMessage:@"正在提交...."];
    [HWWebUtils doPostWithParameters:parametes progress:nil success:^(id response) {
        
        NSString *codeStr =  [NSString stringWithFormat:@"%@",response[@"code"]];
          //   [MBProgressHUD hideHUD];
             
             
             if ([codeStr intValue] == 1) {
              
                 [self.navigationController popViewControllerAnimated:YES];
                 [MBProgressHUD  showError:@"提交成功"];
    

             } else {
                 
                    [MBProgressHUD  showError:response[@"message"]];
                 
             }
             NSLog(@"%@",response);
        
    } failure:^(NSString *error) {
         [MBProgressHUD  showError:@"加载失败"];
 
    }];
 
 
    
    
    
    
    
}





- (NSString *)gs_jsonStringCompactFormatForNSArray:(NSArray *)arrJson {

    // 游戏截图

    if (![arrJson isKindOfClass:[NSArray class]] || ![NSJSONSerialization isValidJSONObject:arrJson]) {

        return nil;

    }


    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arrJson options:0 error:nil];

    NSString *strJson = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

    return strJson;

}













- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view  endEditing:YES];
}


//第一个方法用于限制输入，第二个方法用于动态计算剩余字数
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range

 replacementText:(NSString *)text

{

    UITextRange *selectedRange = [textView markedTextRange];

    //获取高亮部分

    UITextPosition *pos = [textView positionFromPosition:selectedRange.start offset:0];

    //获取高亮部分内容

    //NSString * selectedtext = [textView textInRange:selectedRange];

    

    //如果有高亮且当前字数开始位置小于最大限制时允许输入

    if (selectedRange && pos) {

        NSInteger startOffset = [textView offsetFromPosition:textView.beginningOfDocument toPosition:selectedRange.start];

        NSInteger endOffset = [textView offsetFromPosition:textView.beginningOfDocument toPosition:selectedRange.end];

        NSRange offsetRange = NSMakeRange(startOffset, endOffset - startOffset);

        

        if (offsetRange.location < MAX_LIMIT_NUMS) {

            return YES;

        }

        else

        {
            [MBProgressHUD showError:@"最多只能输入300个字符"];

            return NO;

        }

    }

    

    

    NSString *comcatstr = [textView.text stringByReplacingCharactersInRange:range withString:text];

    

    NSInteger caninputlen = MAX_LIMIT_NUMS - comcatstr.length;

    

    if (caninputlen >= 0)

    {

        return YES;

    }

    else

    {

        NSInteger len = text.length + caninputlen;

        //防止当text.length + caninputlen < 0时，使得rg.length为一个非法最大正数出错

        NSRange rg = {0,MAX(len,0)};

        

        if (rg.length > 0)

        {

            NSString *s = @"";

            //判断是否只普通的字符或asc码(对于中文和表情返回NO)

            BOOL asc = [text canBeConvertedToEncoding:NSASCIIStringEncoding];

            if (asc) {

                s = [text substringWithRange:rg];//因为是ascii码直接取就可以了不会错

            }

            else

            {

                __block NSInteger idx = 0;

                __block NSString  *trimString = @"";//截取出的字串

                //使用字符串遍历，这个方法能准确知道每个emoji是占一个unicode还是两个

                [text enumerateSubstringsInRange:NSMakeRange(0, [text length])

                                         options:NSStringEnumerationByComposedCharacterSequences

                                      usingBlock: ^(NSString* substring, NSRange substringRange, NSRange enclosingRange, BOOL* stop) {

                                          

                                          if (idx >= rg.length) {

                                              *stop = YES; //取出所需要就break，提高效率

                                              return ;

                                          }

                                          

                                          trimString = [trimString stringByAppendingString:substring];

                                          

                                          idx++;

                                      }];

                

                s = trimString;

            }

            //rang是指从当前光标处进行替换处理(注意如果执行此句后面返回的是YES会触发didchange事件)

            [textView setText:[textView.text stringByReplacingCharactersInRange:range withString:s]];

            //既然是超出部分截取了，哪一定是最大限制了。

         //   self.remainLabel.text = [NSString stringWithFormat:@"您最多还可以输入%d个字",0];

        }
        
        
         [MBProgressHUD showError:@"最多只能输入120个字符"];

        return NO;

    }

    

}

 

- (void)textViewDidChange:(UITextView *)textView

{

    UITextRange *selectedRange = [textView markedTextRange];

    //获取高亮部分

    UITextPosition *pos = [textView positionFromPosition:selectedRange.start offset:0];

    

    //如果在变化中是高亮部分在变，就不要计算字符了

    if (selectedRange && pos) {

        return;

    }

    

    NSString  *nsTextContent = textView.text;

    NSInteger existTextNum = nsTextContent.length;

    

    if (existTextNum > MAX_LIMIT_NUMS)

    {

        //截取到最大位置的字符(由于超出截部分在should时被处理了所在这里这了提高效率不再判断)

        NSString *s = [nsTextContent substringToIndex:MAX_LIMIT_NUMS];

        

        [textView setText:s];

    }

    

    //不让显示负数

 //   self.remainLabel.text = [NSString stringWithFormat:@"您最多还可以输入%ld个字",MAX(0,MAX_LIMIT_NUMS - existTextNum)];

}






/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
